<?php
namespace app\api\controller;

use app\BaseController;
use app\model\Device as SelfModel;
use app\model\Project;
use app\model\LeasingCompany;

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Cookie;
use think\Response;
use think\Request;
class Device extends Base
{


    public function initialize()
    {
        parent::initialize();
        $this->model = "\app\model\Device";
        $this->list_rows = 10;
        $this->index = ['error','id','title','project_title','start_time','end_time','delay_time','online_status','use_status','remote_status','remark','create_time'];
        $this->all = ['error','id','title','project_id','project_title','company_title','company_id','start_time','end_time','online_status','use_status','create_time'];
        $this->my = ['error','id','title','project_id','project_title','company_title','company_id','start_time','end_time','online_status','use_status','create_time'];
        $this->view = ['error','id','title','project_title','start_time','end_time','delay_time','online_status','use_status','remote_status','remark','create_time'];
        $this->msg = '设备';

    }

    public function index(Request $request)
    {

        try {
            $data = $this->model::withSearch(array_keys($request->data), $request->data)
                ->field($this->index)
//                ->withoutField($this->without_field)
//                ->where($this->status)
                ->where($this->where)
                ->field(['id','zuofei','title','id_no','name_no','use_status','remote_status','online_status','is_rent_title','rent_start_time','rent_end_time','project_title','remark','start_time','end_time','create_time'])
                ->order($this->order)
                ->paginate($this->list_rows)->each(function ($item,$key){
                    $use_status = empty($item['zuofei']) ? $item['use_status'] :$item['zuofei'];
                    $item['use_status'] = $use_status;

                });
            if($this->append){
                $data->append($this->append);
            }
            if($this->hidden){
                $data->hidden($this->hidden);
            }

            return ['code' => 200, 'msg' => $this->msg . '列表', 'data' => $data,'refresh'=>'y'];
        } catch (\Exception $e) {
            return ['code'=>$e->getCode(),'msg'=>$e->getMessage(),'line'=>$e->getTrace(),'refresh'=>'y'];
        }
    }

    public function view(Request $request)
    {

        try {
            $data = $this->model::withSearch(array_keys($request->data), $request->data)->field(['id','title','id_no','name_no','use_status','remote_status','online_status','is_rent_title','rent_start_time','rent_end_time','project_title','remark','start_time','end_time','delay_time','create_time'])->find();
            if(!empty($data['error'])){
                $this->model::where('title',$data['title'])->update(['error'=>'']);
            }
            return ['code' => 200, 'msg' => $this->msg . '详情', 'data' => $data];
        } catch (\Exception $e) {
            return ['code' => $e->getCode(), 'msg' => $e->getMessage(),];
        }
    }

    public function open(Request $request)
    {
        $device_name = \app\model\Device::where('id','in',$request->id)->select();
        foreach ($device_name as $v){
            (new Aliyuniot())->pub('Openn',$v['title'],$v['id']);
        }
        return ['code' => 200, 'msg' => '开机指令已发送'];
    }

    public function set_project(Request $request)
    {
        $model = (new \app\model\Device())->where('id','in',$request->device_id)->select();
        foreach ($model as $v){
            $v->save(['project_id'=>$request->project_id]);
        }
         return ['code' => 200, 'msg' => '设备设置项目成功'];
    }

    public function cancel_project(Request $request)
    {
        $model = (new \app\model\Device())->where('id','in',$request->device_id)->select();
        foreach ($model as $v){
            $v->save(['project_id'=>0]);
        }
        return ['code' => 200, 'msg' => '取消设置项目成功'];
    }


    public function close(Request $request)
    {
        $device_name = \app\model\Device::where('id','in',$request->id)->select();
        foreach ($device_name as $v){
            (new Aliyuniot())->pub('Close',$v['title'],$v['id']);
        }
        return ['code' => 200, 'msg' => '关机指令已发送'];
    }

    public function export(Request $request)
    {

        $list =  $data = $this->model::withSearch(array_keys($request->data), $request->data)
            ->field($this->index)
//                ->withoutField($this->without_field)
//                ->where($this->status)
            ->where($this->where)
            ->field(['id','title','id_no','name_no','use_status','remote_status','online_status','is_rent_title','rent_start_time','rent_end_time','project_title','remark','start_time','end_time','create_time'])
            ->order($this->order)
            ->select();

        $spreadsheet = new Spreadsheet();
//        $spreadsheet->setActiveSheetIndex(0);
        $sheet = $spreadsheet->getActiveSheet()->setTitle('工时记录');
        $title_arg = ['ID','序号','铭牌号','设备号','项目名称','启租状态','吊篮状态','远程状态','在线状态','年费开始时间','年费结束时间','年费延迟时间','启租时间','停租时间','备注'];
        for ($i=1;$i<=count($title_arg);$i++){
            $sheet->setCellValueByColumnAndRow($i,1,  $title_arg[$i-1]);
        }

        foreach ($list as $k => $v) {
            $j = $k + 2;
            $sheet->setCellValueByColumnAndRow(1, $j, $v['id']);
            $sheet->setCellValueByColumnAndRow(2, $j, $v['id_no']);
            $sheet->setCellValueByColumnAndRow(3, $j, $v['name_no']);
            $sheet->setCellValueByColumnAndRow(4, $j, $v['title']);
            $sheet->setCellValueByColumnAndRow(5, $j, $v['project_title']);
            $sheet->setCellValueByColumnAndRow(6, $j, $v['is_rent_title']);
            $sheet->setCellValueByColumnAndRow(7, $j, $v['use_status']);
            $sheet->setCellValueByColumnAndRow(8, $j, $v['remote_status']);
            $sheet->setCellValueByColumnAndRow(9, $j, $v['online_status']);
            $sheet->setCellValueByColumnAndRow(10, $j, $v['start_time']);
            $sheet->setCellValueByColumnAndRow(11, $j, $v['end_time']);
            $sheet->setCellValueByColumnAndRow(12, $j, $v['delay_time']);
            $sheet->setCellValueByColumnAndRow(13, $j, $v['rent_start_time']);
            $sheet->setCellValueByColumnAndRow(14, $j, $v['rent_end_time']);
            $sheet->setCellValueByColumnAndRow(15, $j, $v['remark']);

        }

//        $spreadsheet->createSheet()->setTitle('员工总工时');;
//        $spreadsheet->setActiveSheetIndex(1);
//        $sheet = $spreadsheet->getActiveSheet(1);

//        $sheet->setCellValue('A1', 'Hello World !');
        $filename ='设备导出.xls';
//        // Redirect output to a client’s web browser (Xls)
//        header('Content-Type: application/vnd.ms-excel');
//        header('Content-Disposition: attachment;filename="'.$filename.'"');
//        header('Cache-Control: max-age=0');
//// If you're serving to IE 9, then the following may be needed
//        header('Cache-Control: max-age=1');
//
//// If you're serving to IE over SSL, then the following may be needed
//        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
//        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
//        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
//        header('Pragma: public'); // HTTP/1.0

        //$writer = IOFactory::createWriter($spreadsheet, 'Xls');

//
//        $writer->save('php://output');
//        exit;
        $name = '设备导出:';
        $company_name = LeasingCompany::where('id',$request->company_id)->value('title');
        $project_name = Project::where('id',$request->project_id)->value('title');
        if(!empty($company_name)){
            $name .=$company_name;
        }
        if(!empty($project_name)){
            $name .= '-'.$project_name;
        }
        $writer = new Xlsx($spreadsheet);
//        $name=rand(10,99);
        $writer->save('./excel/'.$name.'.xlsx');
        return ['code'=>200,'msg'=>'设备导出','url'=> $request->domain().'/excel/'.$name.'.xlsx'];
    }

    public function open_rent(Request $request)
    {
        $deivce = (new \app\model\Device())->where([['id','in',$request->id]])->select();
        foreach ($deivce as $v){
            $v->save(['is_rent'=>'2']);
        }
        return ['code' => 200, 'msg' => '批量启租成功','data'=>$deivce];
    }

    public function close_rent(Request $request)
    {
        $deivce = (new \app\model\Device())->where([['id','in',$request->id]])->select();
        foreach ($deivce as $v){
            $v->save(['is_rent'=>'1']);
        }
        return ['code' => 200, 'msg' => '批量停租成功','data'=>$deivce];
    }


    /*
     * 删除
     */
    public function destory(Request $request)
    {

        $ret = $this->model::where('id','in',$request->id)->update(['zuofei' => '作废']);
        if ($ret) return ['code' => 200, 'msg' => $this->msg . '作废成功,ID=' . $request->id,'count'=>$ret];
        return ['code' => 400, 'msg' => '失败'];
    }



}
